// @ts-check
"use strict";

const { default: path } = require("node:path");
const axios = require("axios");

const bodyParser = require("body-parser");
// const compress = require("compression");
const express = require("express");
const sirv = require("sirv");

const assets = sirv(path.resolve("./public"), {
  maxAge: 86400, // 1day
  immutable: true,
});

const app = express();

const port = 8096;

const toPort = 8888;

// 处理所有请求方法（GET、POST等）
app.use(assets).all("*", async (req, res) => {
  try {
    // 记录请求信息
    console.log("------------------------");
    console.log(`[${new Date().toISOString()}] 收到请求：`);
    console.log(`方法：${req.method}`);
    console.log(`路径：${req.originalUrl}`);
    console.log("请求头：", req.headers);
    console.log("请求参数：", req.query);

    // 构建转发配置
    const config = {
      method: req.method,
      url: `http://127.0.0.1:${toPort}${req.originalUrl}`,
      headers: { ...req.headers },
      data: req.body,
    };

    // 删除可能引起问题的host头
    delete config.headers.host;

    // 转发请求
    const response = await axios(config);

    // 返回响应
    res.status(response.status).set(response.headers).send(response.data);
  } catch (error) {
    console.error("转发请求时出错:", error);
    res.status(500).send("请求转发失败");
  }
});

// // 解析请求体（支持JSON和表单格式）
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: true }));

app.listen(port, () => {
  console.log(`中间件服务运行在 http://127.0.0.1:${port}`);
  console.log(`请确保目标服务运行在 http://127.0.0.1:${toPort}`);
});
